package com.github.yeecode.mybatisdemo.reflect;

import org.apache.ibatis.reflection.Reflector;

import java.lang.reflect.Field;

/**
 * @author : wushikai
 * <p>
 * date : 2021-01-15
 */
public class MyPropertyCopier {

    private MyPropertyCopier() {
        // Prevent Instantiation of Static Class
    }

    public static void copyBeanProperties(Class<?> type, Object sourceBean, Object destinationBean) {
        Class<?> parent = type;
        while (parent != null) {
            final Field[] fields = parent.getDeclaredFields();
            for (Field field : fields) {
                try {


                    try {
                        field.set(destinationBean, field.get(sourceBean));
                    } catch (IllegalAccessException e) {
                        if (Reflector.canControlMemberAccessible()) {
                            field.setAccessible(true);
                            //field 应该包含了类名
                            field.set(destinationBean, field.get(sourceBean));
                            System.out.println("field.getName() = " + field.getName());
                            System.out.println("field.getDeclaringClass().getCanonicalName() = " + field.getDeclaringClass().getCanonicalName());
                        } else {
                            throw e;
                        }
                    }
                } catch (Exception e) {

                }
            }
            // 本类执行完成后，查看父类, 为什么呢???
            parent = parent.getSuperclass();
        }
    }

}
